package com.rdc.qingkou.ui;

import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.rdc.qingkou.Application.MyApplication;
import com.rdc.qingkou.R;
import com.rdc.qingkou.config.URL;
import com.rdc.qingkou.contract.UserInfoContract;
import com.rdc.qingkou.entity.ModifyUserInfoResult;
import com.rdc.qingkou.presenter.UserInfoPresenter;
import com.rdc.qingkou.utils.ACache;
import com.rdc.qingkou.utils.MyUtils;

import java.io.File;

import de.hdodenhof.circleimageview.CircleImageView;

import static com.rdc.qingkou.config.Constant.REQUEST_CODE_WRITE_EXTERNAL_STORAGE;
import static com.rdc.qingkou.utils.MyUtils.bitmap2Bytes;
import static com.rdc.qingkou.utils.MyUtils.getFileFromBytes;


public class PersonalInfoActivity extends AppCompatActivity implements UserInfoContract.IView{

    private String TAG = "PersonalInfoActivity";

    @Override
    protected Dialog onCreateDialog(int id) {
        return super.onCreateDialog(id);
    }

    private CircleImageView personalInfo_portrait_CircleImageView;
    private TextView personalInfo_userName_textView;
    private TextView personalInfo_gender_textView;
    private TextView personalInfo_signature_textView;

    private Bitmap bitmap;
    private ImageView imageView;
    private Drawable drawable;
    private BitmapDrawable bitmapDrawable;

    private UserInfoPresenter mUserInfoPresenter;
    private ACache aCache;
    private String[] genders = new String[]{"女","男"};

    private AlertDialog.Builder alertDialogBuilder;
    private AlertDialog alertDialog;

    @Override
    protected void onResume() {
        super.onResume();
        mUserInfoPresenter.getUserInfo(MyApplication.getUser().getUserId());
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MyApplication.addActivity(this);
        setContentView(R.layout.activity_personal_info);

        aCache = ACache.get(this);

        mUserInfoPresenter = new UserInfoPresenter(this);
//        mUserInfoPresenter.getUserInfo(MyApplication.getUser().getUserId());

        personalInfo_portrait_CircleImageView = (CircleImageView) findViewById(R.id.personalInfo_portrait_CircleImageView);
        personalInfo_userName_textView = (TextView) findViewById(R.id.personalInfo_userName_textView);
        personalInfo_gender_textView = (TextView) findViewById(R.id.personalInfo_gender_textView);
        personalInfo_signature_textView = (TextView) findViewById(R.id.personalInfo_signature_textView);

        findViewById(R.id.btn_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        findViewById(R.id.personalInfo_portrait_relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(!MyUtils.isGrantExternalRW(PersonalInfoActivity.this)){      //to see if the permission has been granted
                    Log.d(TAG, "PERMISSION DENIED !?");
                }else {
                    Log.d(TAG, "PERMISSION ACCESSED");
                    selectPhoto();
                }
            }
        });
        findViewById(R.id.personalInfo_userName_relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transportSculpture();
                startActivity(new Intent(PersonalInfoActivity.this,ModifyNameActivity.class));
            }
        });
        findViewById(R.id.personalInfo_gender_relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                alertDialogBuilder = new AlertDialog.Builder(PersonalInfoActivity.this).setTitle("选择你的性别").setSingleChoiceItems(genders, Integer.parseInt(aCache.getAsString("gender")), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {

                        File image = null;
                        if (personalInfo_portrait_CircleImageView.getDrawable() != null){
                            image = getFileFromBytes(bitmap2Bytes(((BitmapDrawable)(personalInfo_portrait_CircleImageView.getDrawable())).getBitmap()),"file:///sdcard/output_image2.jpg");
                        }
                        switch (which){
                            case 0:
                                aCache.put("gender","0");
                                personalInfo_gender_textView.setText("女");
                                mUserInfoPresenter.modifyUserInfo(image,
                                        0,
                                        aCache.getAsString("nickName"),
                                        aCache.getAsString("signature"),
                                        MyApplication.getUser().getUserId());
                                alertDialog.dismiss();
                                break;
                            case 1:
                                aCache.put("gender","1");
                                personalInfo_gender_textView.setText("男");
                                mUserInfoPresenter.modifyUserInfo(image,
                                        1,
                                        aCache.getAsString("nickName"),
                                        aCache.getAsString("signature"),
                                        MyApplication.getUser().getUserId());
                                alertDialog.dismiss();
                                break;
                        }
                    }
                });

                alertDialog = alertDialogBuilder.show();
            }
        });
        findViewById(R.id.personalInfo_signature_relativeLayout).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transportSculpture();
                startActivity(new Intent(PersonalInfoActivity.this,ModifySignatureActivity.class));
            }
        });
    }

    public void selectPhoto() {
        Intent intent = new Intent(PersonalInfoActivity.this,SculpturePreviewActivity.class);
        bitmap = personalInfo_portrait_CircleImageView.getDrawingCache();     //NULL?
        if (bitmap != null){
            Log.d("PersonalInfoActivity","BITMAP IS NOT NULL");
        }
        if (personalInfo_portrait_CircleImageView.getDrawable() != null){
            Log.d("PersonalInfoActivity","getDrawable() IS NOT NULL");
            aCache.put("drawable",personalInfo_portrait_CircleImageView.getDrawable());
        }
        startActivity(intent);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_WRITE_EXTERNAL_STORAGE : {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //permission granted
                    selectPhoto();
                } else {
                    Toast.makeText(this, "更改头像需要相应的权限！", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }

    public void transportSculpture(){

        drawable = (Drawable)personalInfo_portrait_CircleImageView.getDrawable();
        bitmapDrawable = (BitmapDrawable)drawable;

        if (bitmap != null){
            Log.d("PersonalInfoActivity","BITMAP IS NOT NULL2");
            bitmap = bitmapDrawable.getBitmap();
            aCache.put("sculpture",bitmap2Bytes(bitmap));  //imageView->bitmap->byte[]
        }
    }

    @Override
    public void showData(ModifyUserInfoResult modifyUserInfoResult) {

        Log.d("PersonalInfoActivity","SHOW DATA");

//        Glide.with(this).load(URL.HEAD_YUN+modifyUserInfoResult.getUser().getImageUrl()).asBitmap()
//                .placeholder(R.drawable.imageview_default).dontAnimate().into(personalInfo_portrait_CircleImageView);

        if (modifyUserInfoResult.getUser().getImageUrl() != null){
            Log.d("PersonalInfoActivity","IMAGE URL : "+modifyUserInfoResult.getUser().getImageUrl());
            Glide.with(this).load(URL.HEAD_YUN2+modifyUserInfoResult.getUser().getImageUrl()).asBitmap().into(personalInfo_portrait_CircleImageView);
            MyApplication.getUser().setImageUrl(modifyUserInfoResult.getUser().getImageUrl());
        }else {
            personalInfo_portrait_CircleImageView.setImageDrawable(getResources().getDrawable(R.drawable.user));
        }
//        personalInfo_userName_textView.setText(modifyUserInfoResult.getUser().getNickName());

        if (modifyUserInfoResult.getUser().getNickName() != null){
            personalInfo_userName_textView.setText(modifyUserInfoResult.getUser().getNickName().replace("\"",""));
            aCache.put("nickName",modifyUserInfoResult.getUser().getNickName().replace("\"",""));
            MyApplication.getUser().setNickName(modifyUserInfoResult.getUser().getNickName().replace("\"",""));
        } else {
            personalInfo_userName_textView.setText("Candy");
        }

        if (modifyUserInfoResult.getUser().getSex() == 0){
            personalInfo_gender_textView.setText("女");
            aCache.put("gender","0");
            MyApplication.getUser().setSex(0);
        }else {
            personalInfo_gender_textView.setText("男");
            aCache.put("gender","1");
            MyApplication.getUser().setSex(1);
        }
        if (modifyUserInfoResult.getUser().getSignature() != null){
            personalInfo_signature_textView.setText(modifyUserInfoResult.getUser().getSignature().replace("\"",""));
            aCache.put("signature",modifyUserInfoResult.getUser().getSignature().replace("\"",""));
            MyApplication.getUser().setSignature(modifyUserInfoResult.getUser().getSignature().replace("\"",""));
        }else {
            personalInfo_signature_textView.setText("每一首情歌忽然充满意义，我就在此刻突然见到你");
        }
    }

    @Override
    public void showModifyResult(ModifyUserInfoResult modifyUserInfoResult) {
        Log.d("PersonalInfoActivity","RESULT : " + modifyUserInfoResult.getResult());
        Toast.makeText(PersonalInfoActivity.this,"更改性别成功！",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showInfo(String info) {
        Log.d("PersonalInfoActivity","ERROR RESULT : " + info);
    }
}
